package tij4.concurrent.exercise.ex31;

import java.util.concurrent.*;

public class Ex31 {
    public static void main(String[] args) throws Exception {
        LinkedBlockingQueue<Chopstick> bin = new LinkedBlockingQueue<>();
        int ponder = 0; //即使为0也不会死锁
        if(args.length > 0) {
            ponder = Integer.parseInt(args[0]);
        }
        int size = 2;   //如果筷子就两个会发生死锁
        if(args.length > 1) {
            size = Integer.parseInt(args[1]);
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        Chopstick[] chopsticks = new Chopstick[size];
        for (int i = 0; i < size; i++) {
            chopsticks[i] = new Chopstick();
            bin.put(chopsticks[i]);
        }
        for (int i = 0; i < size; i++) {
            executorService.execute(
                    new Philosopher( chopsticks[i], chopsticks[(i+1) % size], bin, i, 1));
        }
        if (args.length == 3 && args[2].equals("timeout"))
            TimeUnit.SECONDS.sleep(5);
        else {
            System.out.println("Press 'Enter' to quit");
            System.in.read();
        }
        executorService.shutdownNow();

    }
}
